package com.itlong.cloud.config.filelistener;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class CustomMultipartResolver extends CommonsMultipartResolver {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(FileUploadProgressListener.class);

    @Autowired
    private FileUploadProgressListener listener;

    @Autowired
    RedisService redisService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    private String uploadFilePath = "/smartCommunity/interface/device/uploadLogFiles";

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request){
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        fileUpload.setProgressListener(listener);
        String sn = "";
        String deviceType = "";
        String deviceUnique = "";
        String fileName = "";
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            log.info("报头数据》》》》》》》》》》》》》" + name + "》》》》》》》》》》》》》》value>>>>>>>>>>>>>>>>>>>>>>" + request.getHeader(name));
        }

        try {
            if (uploadFilePath.equals(request.getServletPath()) && null != request.getHeader("sn")){
                //获取所有请求头名称
//                Enumeration<String> headerNames = request.getHeaderNames();
//                while (headerNames.hasMoreElements()) {
//                    String name = headerNames.nextElement();
                    //根据名称获取请求头的值
                    if(null == request.getHeader("sn")){
                        throw new DataAccessException("缺少必要参数sn");
                    }
                    sn = request.getHeader("sn");
                    deviceType = request.getHeader("deviceType");
                    deviceUnique = request.getHeader("deviceUnique");
                    fileName = request.getHeader("fileName");
//                }
                if(StringUtils.isBlank(deviceUnique)){
                    if("33".equals(deviceType)) {
                        deviceUnique = StringHandlerUtil.getElevatorDeviceUniqueBySn(sn);
                        deviceType = "0";
                    }
                    if("128".equals(deviceType)) {
                        deviceUnique = StringHandlerUtil.getControllerDeviceUniqueBySn(sn);
                        deviceType = "3";
                    }
                    if("17".equals(deviceType) || "22".equals(deviceType) || "23".equals(deviceType) || "24".equals(deviceType) || "18".equals(deviceType)) {
                        if(StringUtils.isNotBlank(request.getHeader("doorNum"))) {
                            StringBuffer sb = new StringBuffer(request.getHeader("doorNum"));
                            for (int i = sb.length(); i < 4; i++) {
                                sb.insert(0, "0");
                            }
                            sn = sn.substring(0, sn.length()-4 ) + sb.toString();
                        }
                        deviceUnique = StringHandlerUtil.getEntranceDeviceUniqueBySn(sn);
                        if("17".equals(deviceType) || "18".equals(deviceType)) {
                            deviceType = "2";
                        }
                        if("22".equals(deviceType)) {
                            deviceType = "4";
                        }
                        if("24".equals(deviceType)) {
                            deviceType = "6";
                        }
                    }
                }

                Map<Object, Object> receiveStatus = new HashMap<>();
                receiveStatus.put("phase", 1);
                receiveStatus.put("createTime", new Date());
                receiveStatus.put("fileName", fileName);
                receiveStatus.put("sn", sn);
                receiveStatus.put("deviceType", deviceType);
                receiveStatus.put("fileSize", 0);
                receiveStatus.put("uploadStatus", 0);
                redisService.set(deviceUnique, 180L, JSON.toJSONString(receiveStatus));
                listener.setSession(request.getSession(), deviceUnique, sn, deviceType, fileName);
            }
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        }catch (Exception ex) {
            if (uploadFilePath.equals(request.getServletPath()) && StringUtils.isNotBlank(sn)){
                Map<Object, Object> receiveStatus = new HashMap<>();
                receiveStatus.put("phase", 0);
                receiveStatus.put("createTime", new Date());
                receiveStatus.put("fileName", fileName);
                receiveStatus.put("sn", sn);
                if(StringUtils.isNotBlank(deviceType)){
                    receiveStatus.put("deviceType", deviceType);
                }
                receiveStatus.put("deviceUnique", deviceUnique);
                receiveStatus.put("fileSize", 0);
                receiveStatus.put("uploadStatus", -1);
                redisService.set(deviceUnique, 180L, JSON.toJSONString(receiveStatus));
                applicationEventPublisher.publishEvent(new UploadErrorEvent(JSON.toJSONString(receiveStatus)));
            }
            throw new MultipartException("Failed to parse multipart servlet request", ex);

        }
    }
}
